package light.im.loginserver.action;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import service.LoginService;

import light.im.ActionName;
import light.im.IAction;
import light.im.IMSession;
import light.im.loginserver.domain.model.Client;
import light.network.Protocol;
import light.network.object.PackObject;

@ActionName("present")
public class PresentAction implements IAction {
	
	ExecutorService threads = Executors.newCachedThreadPool();

	LoginService loginService = LoginService.getInstance();
	
	@Override
	public void execute(final IMSession session, final PackObject request) {
		
		threads.execute(new Runnable() {
			
			@Override
			public void run() {
				String userName = request.getString("user");
				boolean success = loginService.login(session, userName, request.getString("psw"));
				PackObject he = new PackObject();
				he.put("type", "login");
				if(success)
				{
					Client client = loginService.getClient(userName);
					if(client==null)
					{
						he.put("result", Protocol.NO);
					}
					else
					{
						he.put("result", Protocol.YES);
						he.put("session", client.getSessionId());
						he.put("targetIp", client.getIp());
						he.put("targetPort", client.getPort());
					}
				}
				else
				{
					he.put("result", Protocol.NotAuth);
				}
				try {
					session.write(he);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

//	@Override
//	public void fail(IMSession session, Throwable ext) {
//		ext.printStackTrace();
//	}

}
